<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('800px')"
    :visible="visible"
    :title="$t('TEST_PARA')"
    @open="open"
    @close="close"
  >
    <div slot="title" class="text-color">
      {{ $t('TEST_PARA') }}
      <TestParamTips />
    </div>
    <el-form
      ref="otdrParam"
      label-width="auto"
      :model="otdrParam"
      class="flex flex-wrap detect-form pr-20"
      :rules="rules"
    >
      <el-form-item class="w-50 pr-20" :label="$t('TEST_NAME')" prop="processName">
        <el-input v-model.trim="otdrParam.processName" maxlength="32" />
      </el-form-item>
      <el-form-item class="w-50 pl-20" :label="$t('TEST_TEMPLATE')">
        <el-select
          v-model="templateValue"
          clearable
          :placeholder="$t('SELECT_TPL')"
          value-key="taskId"
          @change="selectChange"
        >
          <el-option
            v-for="item in templateList"
            :key="item.taskId"
            :label="item.tempName"
            :value="item"
          >
            <span style="float: left">{{ item.tempName }}</span>
            <span
              style="float: right; color: #8492a6; font-size: 13px"
              @click.stop="deleteTpl(item.taskId)"
            >{{ $t("DEL") }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        class="w-50 pr-20"
        :label="$t('TEST_MODE')"
        prop="testMode"
        required
      >
        <el-select v-model="otdrParam.testMode">
          <el-option
            v-for="item in dictList.OTDR_TEST_MODE.filter(
              (i) => i.value !== 'REALTIME'
            )"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="w-50 pl-20"
        :label="$t('JOINT_LOSS_THRESHOLD')"
        prop="lossThreshold"
      >
        <el-input v-model="otdrParam.lossThreshold" />
      </el-form-item>
      <el-form-item
        class="w-50 pr-20"
        :label="$t('WAVELENGTH')"
        prop="waveLength"
        required
      >
        <el-select v-model="otdrParam.waveLength">
          <el-option
            v-for="item in dictList.WAVE_LENGTH"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="w-50 pl-20"
        :label="$t('ENV_REFLECTION_THR')"
        prop="reflectThreshold"
      >
        <el-input v-model="otdrParam.reflectThreshold" />
      </el-form-item>
      <el-form-item
        class="w-50 pr-20"
        :label="$t('TEST_RANGE')"
        prop="testRange"
        required
      >
        <template v-if="otdrParam.testMode === 'AUTO'">
          <el-input disabled />
        </template>
        <el-select v-else v-model="otdrParam.testRange">
          <el-option
            v-for="item in dictList.TEST_RANGE"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="w-50 pl-20"
        :label="$t('FIBER_END_THR')"
        prop="endThreshold"
      >
        <el-input v-model="otdrParam.endThreshold" />
      </el-form-item>
      <el-form-item
        class="w-50 pr-20"
        :label="$t('PULSE_WIDTH')"
        prop="pulseWidth"
        required
      >
        <template v-if="otdrParam.testMode === 'AUTO'">
          <el-input disabled />
        </template>
        <el-select v-else v-model="otdrParam.pulseWidth">
          <el-option
            v-for="item in dictList.PULSE_WIDTH"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="w-50 pl-20" :label="$t('CORRECTION_PARA')" prop="fixParam">
        <el-input v-model="otdrParam.fixParam" />
      </el-form-item>
      <el-form-item class="w-50 pr-20" :label="$t('INDEX')" prop="refractRate">
        <el-input v-model="otdrParam.refractRate" />
      </el-form-item>
      <el-form-item class="w-50 pl-20" :label="$t('TEST_NUMBER')" prop="testNum">
        <el-input v-model="otdrParam.testNum" />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="close">{{ $t("CANCEL") }}</el-button>
      <el-button
        v-if="type != 'view'"
        type="primary"
        @click="$debounce(save)"
      >{{ $t("START_TEST") }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import taskGroup from '@/api/oen/TaskGroup'
  import otdrTestResult from '@/api/oen/OtdrTestResult'
  import TestParamTips from '@/components/TestParamTips'

  export default {
    components: {
      TestParamTips
    },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      type: {
        type: String,
        default: ''
      },
      formData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        otdrParam: {
          cut: true,
          processName: '',
          testMode: 'AVG',
          waveLength: 1550,
          pulseWidth: 80,
          testRange: 8000,
          lossThreshold: 0.2,
          reflectThreshold: -40,
          endThreshold: 10,
          fixParam: 1,
          refractRate: 1.472,
          testNum: 5
        },
        templateList: [],
        templateValue: ''
      }
    },
    computed: {
      ...mapGetters(['dictList']),
      rules() {
        return {
          processName: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('TEST_NAME'),
              trigger: 'blur'
            }
          ],
          endThreshold: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('FIBER_END_THR'),
              trigger: 'blur'
            },
            {
              pattern: /^[0-9]\d*$/,
              message: this.$t('ONLY_INIT'),
              trigger: ['blur', 'change']
            },
            {
              validator: (valid, value, callback) => {
                this.validatePort(valid, value, callback, this.$t('FIBER_END_THR'), 1, 99)
              },
              trigger: ['blur', 'change']
            }
          ],
          fixParam: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('CORRECTION_PARA'),
              trigger: 'blur'
            },
            {
              pattern: /^(0|([1-9]\d*))(\.\d{1,3})?$/,
              message: this.$t('ONLY_FLOAT', { count: 3 }),
              trigger: ['blur', 'change']
            }
          ],
          lossThreshold: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('JOINT_LOSS_THRESHOLD'),
              trigger: 'blur'
            },
            {
              pattern: /^(0|([1-9]\d*))(\.\d{1,2})?$/,
              message: this.$t('ONLY_FLOAT', { count: 2 }),
              trigger: ['blur', 'change']
            },
            {
              validator: (valid, value, callback) => {
                this.validatePort(valid, value, callback, this.$t('JOINT_LOSS_THRESHOLD'), 0.01, 9.99)
              },
              trigger: ['blur', 'change']
            }
          ],
          reflectThreshold: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('ENV_REFLECTION_THR'),
              trigger: 'blur'
            },
            { pattern: /^[-]?(0|([1-9]\d*))(\.\d{1})?$/, message: this.$t('ONLY_FLOAT', { count: 1 }), trigger: ['blur', 'change'] },
            { validator: (valid, value, callback) => {
              this.validatePort(valid, value, callback, this.$t('ENV_REFLECTION_THR'), -65, -14)
            }, trigger: ['blur', 'change'] }
          ],
          refractRate: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('INDEX'),
              trigger: 'blur'
            },
            {
              pattern: /^(0|([1-9]\d*))(\.\d{1,3})?$/,
              message: this.$t('ONLY_FLOAT', { count: 3 }),
              trigger: ['blur', 'change']
            },
            {
              validator: (valid, value, callback) => {
                this.validatePort(valid, value, callback, this.$t('INDEX'), 0, 99)
              },
              trigger: ['blur', 'change']
            }
          ],
          testNum: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('TEST_NUMBER'),
              trigger: 'blur'
            },
            {
              pattern: /(^[0-9]\d*$)/,
              message: this.$t('ONLY_INIT'),
              trigger: ['blur', 'change']
            },
            {
              validator: (valid, value, callback) => {
                this.validatePort(valid, value, callback, this.$t('TEST_NUMBER'), 1, 9999)
              },
              trigger: ['blur', 'change']
            }
          ]
        }
      }
    },
    methods: {
      getTemplate() {
        otdrTestResult.getTemplateList().then((res) => {
          if (res) {
            this.templateList = [...res]
          }
        })
      },
      open() {
        console.log('this.formData', this.formData)
        this.templateValue = ''
        this.otdrParam = this.$options.data().otdrParam
        this.getTemplate()
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate()
        })
      },
      save() {
        this.$refs.otdrParam.validate((valid) => {
          if (!valid) {
            return false
          }
          const requestData = {
            ...this.formData,
            otdrParam: { ...this.otdrParam },
            processName: this.otdrParam.processName,
            cut: this.otdrParam.cut,
            linkSegmentId: this.formData.segmentId
          }
          delete requestData.otdrParam.processName
          delete requestData.otdrParam.cut
          taskGroup.detect(requestData).then((res) => {
            this.otdrParam = this.$options.data().otdrParam
            this.$message.success(this.$t('REQUEST_SUCCESS'))
            this.$router.push({
              name: 'MENU_PROCESS_LIST',
              params: {
                processId: res.processId,
                taskId: res.taskIdList
              }
            })
            this.close(true)
          })
        })
      },
      close(load) {
        this.$refs.otdrParam.clearValidate()
        this.$emit('close', load)
      },
      selectChange(obj) {
        if (obj) {
          obj.testParam.processName = this.otdrParam.processName
          this.otdrParam = { ...obj.testParam, cut: this.otdrParam.cut }
          this.otdrParam.testRange = obj.testParam.testRange
          this.otdrParam.taskId = obj.taskId // 标记使用了哪个模板
        } else {
          this.$refs.otdrParam.resetFields()
        }
      },
      deleteTpl(id) {
        otdrTestResult.removeTemplate(id).then((res) => {
          if (res) {
            this.$message.success(this.$t('DELETE_SUCCESS'))
            this.getTemplate()
            if (this.otdrParam.taskId) {
              if (this.otdrParam.taskId === id) {
                // 选中的模板被删除，就要重置测试参数
                this.$refs.otdrParam.resetFields()
              }
            }
          }
        })
      },
      validatePort(rule, value, callback, name, min = 1, max) {
        if (Number(value) > Number(max) || Number(value) < Number(min)) {
          callback(
            new Error(this.$t('VALUE_RANGE', { name: name, min: min, max: max }))
          )
        } else {
          callback()
        }
      }
    }
  }
</script>

<style scoped>
</style>
